import T from 'ant-design-vue/es/table/Table'
import get from 'lodash.get'
import lodash from 'lodash'
import i18n from '@/lang'
import { minxinGetDomHeight } from '@/utils/mixin'
import tableDraggable from '@/utils/tableDraggable'
import tbColAliginMixin from '@/utils/tbColAliginMixin'
import TbColumnFilter from '@/components/TbColumnFilter/index2'
import {mapState} from 'vuex'
import md5 from 'md5'
const orderType = {
  ascend: 'ASC',
  descend: 'DESC'
}
let index = 0;
export default {
  components:{
    TbColumnFilter
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  mixins: [minxinGetDomHeight, tbColAliginMixin],
  data() {
    let id = 'table' + ++index;
    return {
      checked:true,
      sorter: {},
      needTotalList: [],
      selectedRows: [],
      selectedRowKeys: [],
      localLoading: false,
      localDataSource: [],
      localPagination: Object.assign({}, T.props.pagination),
      wrapRef: 'tableWrapperRef',
      id: id,
      expectCls: '.table-wrapper #' + id + ' .ant-table-thead',
      svSelfDefineAntTbDivCls: '#' + id + ' '
    }
  },
  props: Object.assign({}, T.props, {
    // 确保唯一，用于自定义表格存储
    tableId: {
      type: String,
      default: ''
    },
    columns: {
      type: Array,
      default: null
    },
    // 是否显示列设置图标
    showFilter:{
      type: Boolean,
      default: true
    },
    rowKey: {
      type: [String, Function],
      default: 'id'
    },
    data: {
      type: [Function, Array],
      required: false
    },
    pageNum: {
      type: Number,
      default: 1
    },
    pageSize: {
      type: Number,
      default: 20
    },
    pageSizeOptions: {
      type: Array,
      default: () => ['10', '20', '50', '100']
    },
    showSizeChanger: {
      type: Boolean,
      default: true
    },
    size: {
      type: String,
      default: 'default'
    },
    // 表格的底部
    hasFooter: {
      type: Boolean,
      default: false
    },
    /**
     * {
     *   show: true,
     *   clear: Function
     * }
     */
    alert: {
      type: [Object, Boolean],
      default: null
    },
    rowSelection: {
      type: Object,
      default: null
    },
    /** @Deprecated */
    showAlertInfo: {
      type: Boolean,
      default: false
    },
    showPagination: {
      type: String | Boolean,
      default: true
    },
    dataSource: {
      type: Array,
      default() {
        return []
      }
    },
    loading: {
      type: Boolean,
      default: false
    },
    onChangeTable: {
      type: Function,
      default: null
    },
    scrollX: {
      type: Number,
      default: 0
    },
    offset: {
      type: Number,
      default: 0
    },
    /**
     * 是否给行数据增加loading字段，用于控制行的操作loading
     */
    addLoading: {
      type: Boolean,
      default: false
    }
  }),
  watch: {
    'localPagination.current'() {
      //检测到当前页变化时调用
      this.getPagination()
    },
    pageNum(val) {
      Object.assign(this.localPagination, {
        current: val
      })
      this.getPagination()
    },
    pageSize(val) {
      Object.assign(this.localPagination, {
        pageSize: val
      })
      this.getPagination()
    },
    showSizeChanger(val) {
      Object.assign(this.localPagination, {
        showSizeChanger: val
      })
      this.getPagination()
    },
    // 直接传递数据的时候，此时不用data属性，使用dataSource属性
    dataSource: {
      handler(val) {
        if (!this.data) {
          this.localDataSource = val
        }
      },
      immediate: true
    },
    loading: {
      handler(val) {
        console.log(val, 'loading')
        this.localLoading = val
      },
      immediate: true
    }
  },
  created() {
   
    if (!this.data) { 
      //使用dateSource属性 传值数组
      return
    }
    //使用data属性传值，data为一个函数
    this.localPagination =
      //是否展示分页器
      ['auto', true].includes(this.showPagination) &&
      Object.assign({}, this.localPagination, {
        current: this.pageNum,
        pageSize: this.pageSize,
        pageSizeOptions: this.pageSizeOptions,
        showSizeChanger: this.showSizeChanger,
        size: 'small',
        showQuickJumper: true,
        showTotal: (total) => `Total ${total} items`
      })
    this.needTotalList = this.initTotalList(this.columns)
    this.loadData()
    this.getPagination()
    console.log('created...')
  },
  methods: {
    // 获取table的分页情况
    getPagination() {
      this.$emit('getPagination', this.localPagination)
    },
    /**
     * 表格重新加载方法
     * 如果参数为 true, 则强制刷新到第一页
     * @param Boolean bool
     */
    refresh(bool = false) {
      bool &&
        (this.localPagination = Object.assign(
          {},
          {
            current: 1,
            pageSize: this.pageSize
          }
        ))
      this.loadData()
    },
    /**
     * 加载数据方法
     * @param {Object} pagination 分页选项器
     * @param {Object} filters 过滤条件
     * @param {Object} sorter 排序条件
     */
    loadData(pagination, filters, sorter) {
      console.log('执行');
      this.localDataSource = []
      if ((!sorter || !sorter.order) && this.order) {
        // eslint-disable-next-line no-param-reassign
        sorter = this.order
      }
      const parameter = Object.assign(
        {
          pageNo: (pagination && pagination.current) || this.localPagination.current || this.pageNum,
          pageSize: (pagination && pagination.pageSize) || this.localPagination.pageSize || this.pageSize
        },
        {
          ...filters
        }
      )
      if (sorter && sorter.columnKey) {
        if (sorter.order) {
          parameter.order = `${sorter.columnKey},${orderType[sorter.order]}`
        } else {
          parameter.order = undefined
        }
      }
      const result = this.data(parameter)
      // 对接自己的通用数据接口需要修改下方代码中的 r.pageNo, r.totalPage, r.data
      // eslint-disable-next-line
      if ((typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function') {
        this.localLoading = true
        result
          .then((r) => {
            if (r) {
              this.localPagination = Object.assign({}, this.localPagination, {
                current: r.pageNo || this.localPagination.current || 1, // 返回结果中的当前分页数
                total: r.totalCount || r.data.length, // 返回结果中的总记录数
                showSizeChanger: this.showSizeChanger,
                pageSize: (pagination && pagination.pageSize) || this.localPagination.pageSize
              })
              // 如果请求的当前页没有数据 自动跳到有数据的最后一页
              // eslint-disable-next-line max-len
              if (
                Array.isArray(r.data) &&
                r.data.length === 0 &&
                this.localPagination.current !== 1 &&
                this.localPagination.current > r.totalPage
              ) {
                this.localPagination.current = r.totalPage
                this.loadData()
                return
              }
              // 这里用于判断接口是否有返回 r.totalPage 或 this.showPagination = false
              // 当情况满足时，表示数据不满足分页大小，关闭 table 分页功能

              // eslint-disable-next-line no-mixed-operators
              ; (!this.showPagination || (!r.totalRow && this.showPagination === 'auto')) &&
                (this.localPagination = false)
              if (this.addLoading) {
                r.data.forEach(item => item.loading = false);
              }
              this.localDataSource = r.data.length ? r.data : [] // 返回结果中的数组数据
            }
            this.localLoading = false
          })
          .finally(() => {
            this.localLoading = false
          })
      }
    },
    handleTableChange(pagination, filters, sorter) {
      this.order = sorter
      this.loadData(pagination, filters, sorter)
    },
     //传入的columns中某个数组元素对象带有needTotal属性，获取该数组元素元素
    initTotalList(columns) {
      const totalList = []
      columns &&
        columns instanceof Array &&
        columns.forEach((column) => {
          if (column.needTotal) {
            totalList.push({
              ...column,
              total: 0
            })
          }
        })
      return totalList
    },
    /**
     * 用于更新已选中的列表数据 total 统计
     * @param selectedRowKeys
     * @param selectedRows
     */
    updateSelect(selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
      this.selectedRowKeys = selectedRowKeys
      const list = this.needTotalList
      this.needTotalList = list.map((item) => {
        return {
          ...item,
          total: selectedRows.reduce((sum, val) => {
            // eslint-disable-next-line radix
            const total = sum + parseInt(get(val, item.dataIndex))
            return isNaN(total) ? 0 : total
          }, 0)
        }
      })
    },
    /**
     * 清空 table 已选中项
     */
    clearSelected() {
      if (this.rowSelection) {
        this.rowSelection.onChange([], [])
        this.updateSelect([], [])
      }
    },
    /**
     * 处理交给 table 使用者去处理 clear 事件时，内部选中统计同时调用
     * @param callback
     * @returns {*}
     */
    renderClear(callback) {
      if (this.selectedRowKeys.length <= 0) return null
      return (
        <a
          style="margin-left: 24px"
          onClick={() => {
            this.clearSelected()
            callback()
          }}
        >
          {i18n.t('clear')}
        </a>
      )
    },
    renderAlert() {
      // 绘制统计列数据
      const needTotalItems = this.needTotalList.map((item) => {
        return (
          <span style="margin-right: 12px">
            {item.title}总计{' '}
            <a style="font-weight: 600">{!item.customRender ? item.total : item.customRender(item.total)}</a>
          </span>
        )
      })

      // 绘制 清空 按钮
      const clearItem =
        // eslint-disable-next-line no-nested-ternary
        typeof this.alert.clear === 'boolean' && this.alert.clear
          ? this.renderClear(this.clearSelected)
          : this.alert !== null && typeof this.alert.clear === 'function'
            ? this.renderClear(this.alert.clear)
            : null

      // 绘制 alert 组件
      return (
        <a-alert showIcon={true} style="margin-bottom: 16px">
          <template slot="message">
            <span style="margin-right: 12px">
              {this.$t('selected')}{' '}
              <a style="font-weight: 600">
                {this.selectedRowKeys.length} {this.$t('item')}
              </a>
            </span>
            {needTotalItems}
            {clearItem}
          </template>
        </a-alert>
      )
    },
    changePageSize(page) {
      this.localPagination.current = page
      this.loadData()
    },
    showSizeChange(current, size) {
      this.localPagination.pageSize = size
      this.loadData()
    },
    handleNewCols(headerSetData){
      const userId=this.userInfo.account
      const tableId=this.tableId?this.tableId:md5(JSON.stringify(this.columns))
      localStorage.setItem(`tf_${userId}_${tableId}`, JSON.stringify(headerSetData))
      this.loadData()
    }
  },
  mounted() {
    const vm = this
    // window.removeEventListener('resize', this.getDomHeight)
    //onresize 双重触发保证高度计算准确性
    window.onresize = function () { // 监听屏幕的改变
      vm.getDomHeight();
    }
  },
  activated() {
    this.getDomHeight();
  },
  render() {
    const props = {}
    const localKeys = Object.keys(this.$data)
    // eslint-disable-next-line max-len, no-mixed-operators
    const showAlert =
      (typeof this.alert === 'object' &&
        this.alert !== null &&
        this.alert.show &&
        typeof this.rowSelection.selectedRowKeys !== 'undefined') ||
      this.alert

    Object.keys(T.props).forEach((k) => {
      const localKey = `local${k.substring(0, 1).toUpperCase()}${k.substring(1)}`
      if (localKeys.includes(localKey)) {
        props[k] = this[localKey]
        return props[k]
      }
      if (k === 'rowSelection') {
        if (showAlert && this.rowSelection) {
          // 如果需要使用alert，则重新绑定 rowSelection 事件
          // 如果不用判断checkbox是否可选 则需要默认原始
          // eslint-disable-next-line no-unused-vars
          const defautCheckboxProps = (record) => ({
            props: {}
          })
          props[k] = {
            selectedRows: this.selectedRows,
            selectedRowKeys: this.selectedRowKeys,
            type: this.rowSelection.type || 'checkbox',
            onChange: (selectedRowKeys, selectedRows) => {
              // console.log(selectedRowKeys)
              this.updateSelect(selectedRowKeys, selectedRows)
              typeof this[k].onChange !== 'undefined' && this[k].onChange(selectedRowKeys, selectedRows)
            },
            getCheckboxProps: this.rowSelection.getCheckboxProps || defautCheckboxProps // 控制checkbox是否可选
          }
          return props[k]
          // eslint-disable-next-line no-else-return
        } else if (!this.rowSelection) {
          // 如果没打算开启 rowSelection 则清空默认的选择项
          props[k] = null
          return props[k]
        }
      }
      props[k] = this[k]
      return props[k]
    })
    const hasShowPagination = this.showPagination && this.localPagination.total
    let yVal = hasShowPagination ? this.contentHeight - 50 : this.contentHeight
     // console.log(yVal + 'yval', this. contentHeight + 'content')
    yVal = this.hasFooter ? yVal - 50 : yVal
    let xVal = 0
    props.columns.forEach((column) => {
      const width = column.width * 1
      if (!isNaN(column.width * 1)) {
        xVal += width
      }
    })
    const colName=JSON.parse(localStorage.getItem(`tf_${this.userInfo.account}_${md5(JSON.stringify(this.columns))}`)) || []
    const setCols=[]
    if(colName.length){
      colName.forEach(setData=>{
        this.columns.forEach(originData=>{
          if(setData.show && (setData.title==originData.title || setData.title==originData.titleName)){
            setCols.push(originData)
          }
        })
      })
      this.columns.forEach(item=>{
        if(item.fixed){
          setCols.push(item)
        }
      })
    }
    this.columns.forEach(item=>{
      if(!(item.title || item.titleName)){
        this.checked=false
      }
    })
    props.columns=(setCols.length && setCols) || this.columns
    // tableDraggable(props.columns)
    if (this.draggable !== false) {
      props.components = tableDraggable(props.columns)
    }
    props.scroll = { y: yVal - this.offset }
    if (xVal) {
      props.scroll.x = xVal
    }
    if (this.scrollX) {
      if (xVal && xVal < this.scrollX) {
      } else {
        props.scroll.x = this.scrollX;
      }
    }
    // console.log(props.scroll.x, 'props.scroll.x')
    props.pagination = false
    // console.log('this.$scopedSlots',this.$scopedSlots);
    const table = (
      <a-table id={this.id}
        {...{ props, scopedSlots: { ...this.$scopedSlots } }}
        onChange={this.onChangeTable || this.handleTableChange}
      >
        {Object.keys(this.$slots).map((name) => (
          <template slot={name}>{this.$slots[name]}</template>
        ))}
      </a-table>
    )
    const fliter = (this.showFilter && this.checked && !this.localLoading)?(
      <tb-column-filter columns={this.columns} onHandleNewCols={this.handleNewCols} style="height:0px;width:60px;margin-left:calc(100% - 60px);position:relative;top:1px;z-index:10"></tb-column-filter>
    ) : ''
    // eslint-disable-next-line max-len
    const pagination = (
      <a-pagination pageSizeOptions={['20', '40', '60', '80', '100']}
        pageSize={this.localPagination.pageSize}
        total={this.localPagination.total}
        current={this.localPagination.current}
        onChange={this.changePageSize}
        showTotal={(total) => '共' + total + '条'}
        onShowSizeChange={this.showSizeChange} showQuickJumper showSizeChanger
        size="small"
      />
    )
    return (
      <div class="dsxw-table-pagination-wrapper commonTableSty" style="min-height:200px">
          {fliter}
          <div class="table-wrapper" ref="tableWrapperRef">
            {showAlert ? this.renderAlert() : null}
            {table}
          </div>
          {hasShowPagination ? <div class="pagination-wrapper">{pagination}</div> : ''}
        </div>
    )
  }
}
